package com.example.blog.controller.blog;

import com.example.blog.pojo.Images;
import com.example.blog.pojo.Result;
import com.example.blog.service.ImagesServices;
import com.example.blog.util.PcUtils.UploadFileUtils;
import com.example.blog.util.TokenUtil.GetCookie;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/images")
public class ImagesController {
    @Resource
    private ImagesServices imagesServices;
    //添加博客
    @PostMapping("/add")
    public Result saveImages(Images images, HttpServletRequest request) throws ServletException, IOException {
        String cookieValue = request.getHeader("Cookie");
        String token = GetCookie.getCookieValue(cookieValue);
        Part filePart = request.getPart("avatar");
        if (filePart!=null){
            UploadFileUtils.BlogResult result = UploadFileUtils.savePart(request, filePart);
            images.setPath(result.getUrl());
        }
        return imagesServices.saveImages(images,token);
    }

    @GetMapping("/getUserImages")
    public List<Images> getUserImages( HttpServletRequest request){
        String cookieValue = request.getHeader("Cookie");
        String token = GetCookie.getCookieValue(cookieValue);
        return imagesServices.getUserImages(token);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteImagesRecord(@PathVariable int id,HttpServletRequest request){
        String cookieValue = request.getHeader("Cookie");
        String token = GetCookie.getCookieValue(cookieValue);
        return imagesServices.deleteImagesRecord(id,token);
    }
}
